﻿using System;
using System.Windows.Media;

namespace Silverlight.Media.Encoder.Sinks
{
    public class VideoSampleSink : VideoSink
    {
        public int TimeFactor { get; set; }

        public event EventHandler<VideoFormatChangedArgs> VideoFormatChanged;

        public event EventHandler<OnSampleArgs> OnMediaSample;

        public event EventHandler OnCaptureStart;

        public event EventHandler OnCaptureStop;

        public VideoSampleSink()
        {
            TimeFactor = 1;
        }

        #region Invokers
        private void InvokeOnCaptureStart()
        {
            var e = new EventArgs();
            EventHandler handler = OnCaptureStart;
            if (handler != null) handler(this, e);
        }

        private void InvokeOnCaptureStop()
        {
            var e = new EventArgs();
            EventHandler handler = OnCaptureStop;
            if (handler != null) handler(this, e);
        }

        private void InvokeOnMediaSample(OnSampleArgs e)
        {
            EventHandler<OnSampleArgs> handler = OnMediaSample;
            if (handler != null) handler(this, e);
        }

        private void InvokeVideoFormatChanged(VideoFormatChangedArgs e)
        {
            var handler = VideoFormatChanged;
            if (handler != null) handler(this, e);
        }
        #endregion

        protected override void OnCaptureStarted()
        {
            InvokeOnCaptureStart();
        }

        protected override void OnCaptureStopped()
        {
            InvokeOnCaptureStop();
        }

        protected override void OnFormatChange(VideoFormat videoFormat)
        {
            InvokeVideoFormatChanged(new VideoFormatChangedArgs(videoFormat));
        }

        protected override void OnSample(long sampleTimeInHundredNanoseconds, long frameDurationInHundredNanoseconds, byte[] sampleData)
        {
            sampleTimeInHundredNanoseconds *= TimeFactor;
            frameDurationInHundredNanoseconds *= TimeFactor;

            InvokeOnMediaSample(new OnSampleArgs(sampleTimeInHundredNanoseconds, frameDurationInHundredNanoseconds, sampleData, SampleType.Video));
        }
    }
}
